# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

from concurrent.futures import ThreadPoolExecutor
import requests


class KrakenAsyncFeedClient(object):
  def __init__(self, native_private_client, logger, max_connections=20):
    super().__init__()
    self._native_private_client = native_private_client
    self._logger = logger
    self._executor = ThreadPoolExecutor(max_workers=max_connections)

  def _query_order_book(self, symbol, level):
    try:
      update = self._native_private_client.get_order_book(symbol, level)
      return update
    except requests.exceptions.RequestException as e:
      self._logger.error('RequestException: %s' % e)
      return None
    except AssertionError:
      return None

  def _query_trade(self, symbol, since):
    try:
      update = self._native_private_client.get_recent_trades(symbol, since)
      return update
    except requests.exceptions.RequestException as e:
      self._logger.error('RequestException: %s' % e)
      return None
    except AssertionError:
      return None

  def async_query_order_book(self, symbol, level):
    if self._executor:
      fut = self._executor.submit(self._query_order_book, symbol, level)
      return fut
    return None

  def async_query_trade(self, symbol, since):
    if self._executor:
      fut = self._executor.submit(self._query_trade, symbol, since)
      return fut
    return None

  def stop(self):
    if self._executor:
      self._executor.shutdown(False)
    else:
      self._logger.warning('Already stopped')
    self._executor = None
